import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, Select, message, Popconfirm, Tree } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

const { Option } = Select;

const PermissionManagement = () => {
  const [permissionList, setPermissionList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加权限');
  const [form] = Form.useForm();
  const [currentId, setCurrentId] = useState(null);
  const [expandedKeys, setExpandedKeys] = useState([]);

  // 获取权限列表
  const fetchPermissionList = async () => {
    setLoading(true);
    try {
      // 模拟从API获取数据
      setTimeout(() => {
        const mockPermissions = [
          {
            id: 1,
            name: '仪表盘',
            code: 'dashboard',
            type: 'menu',
            parentId: 0,
            status: 1,
            children: [
              {
                id: 2,
                name: '查看仪表盘',
                code: 'dashboard:view',
                type: 'button',
                parentId: 1,
                status: 1
              }
            ]
          },
          {
            id: 3,
            name: '系统管理',
            code: 'system',
            type: 'menu',
            parentId: 0,
            status: 1,
            children: [
              {
                id: 4,
                name: '用户管理',
                code: 'system:user',
                type: 'menu',
                parentId: 3,
                status: 1,
                children: [
                  {
                    id: 5,
                    name: '查看用户',
                    code: 'system:user:view',
                    type: 'button',
                    parentId: 4,
                    status: 1
                  },
                  {
                    id: 6,
                    name: '添加用户',
                    code: 'system:user:add',
                    type: 'button',
                    parentId: 4,
                    status: 1
                  },
                  {
                    id: 7,
                    name: '编辑用户',
                    code: 'system:user:edit',
                    type: 'button',
                    parentId: 4,
                    status: 1
                  },
                  {
                    id: 8,
                    name: '删除用户',
                    code: 'system:user:delete',
                    type: 'button',
                    parentId: 4,
                    status: 1
                  }
                ]
              },
              {
                id: 9,
                name: '角色管理',
                code: 'system:role',
                type: 'menu',
                parentId: 3,
                status: 1
              },
              {
                id: 10,
                name: '权限管理',
                code: 'system:permission',
                type: 'menu',
                parentId: 3,
                status: 1
              }
            ]
          }
        ];
        setPermissionList(mockPermissions);
        setExpandedKeys(['1', '3', '4']);
        setLoading(false);
      }, 500);
    } catch (error) {
      message.error('获取权限列表失败');
      console.error(error);
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPermissionList();
  }, []);

  // 添加或更新权限
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      message.success(currentId ? '更新成功' : '添加成功');
      setModalVisible(false);
      fetchPermissionList(); // 重新获取列表
    } catch (error) {
      console.error('提交表单失败:', error);
    }
  };

  // 删除权限
  const handleDelete = (id) => {
    message.success('删除成功');
    fetchPermissionList(); // 重新获取列表
  };

  // 打开添加权限模态框
  const showAddModal = (parentId = 0) => {
    setModalTitle('添加权限');
    setCurrentId(null);
    form.resetFields();
    form.setFieldsValue({ 
      parentId, 
      type: 'menu',
      status: 1 
    });
    setModalVisible(true);
  };

  // 打开编辑权限模态框
  const showEditModal = (record) => {
    setModalTitle('编辑权限');
    setCurrentId(record.id);
    form.setFieldsValue({
      ...record,
      parentId: record.parentId
    });
    setModalVisible(true);
  };

  // 表格列配置
  const columns = [
    {
      title: '权限名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '权限标识',
      dataIndex: 'code',
      key: 'code'
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => {
        const typeMap = {
          'menu': '菜单',
          'button': '按钮'
        };
        return typeMap[type] || type;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span>{status === 1 ? '启用' : '禁用'}</span>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 280,
      render: (_, record) => (
        <Space size="middle">
          {record.type === 'menu' && (
            <Button 
              type="primary" 
              size="small"
              onClick={() => showAddModal(record.id)}
            >
              添加子权限
            </Button>
          )}
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此权限吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={() => showAddModal()}
        >
          添加顶级权限
        </Button>
      </div>
      
      <Table 
        columns={columns} 
        dataSource={permissionList} 
        loading={loading}
        pagination={false}
        rowKey="id"
        expandable={{
          defaultExpandAllRows: true
        }}
      />
      
      <Modal
        title={modalTitle}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ type: 'menu', status: 1 }}
        >
          <Form.Item
            name="parentId"
            label="父级权限"
            hidden
          >
            <Input />
          </Form.Item>
          
          <Form.Item
            name="name"
            label="权限名称"
            rules={[{ required: true, message: '请输入权限名称' }]}
          >
            <Input placeholder="请输入权限名称" />
          </Form.Item>
          
          <Form.Item
            name="code"
            label="权限标识"
            rules={[{ required: true, message: '请输入权限标识' }]}
          >
            <Input placeholder="请输入权限标识，如：system:user:view" />
          </Form.Item>
          
          <Form.Item
            name="type"
            label="权限类型"
            rules={[{ required: true, message: '请选择权限类型' }]}
          >
            <Select>
              <Option value="menu">菜单</Option>
              <Option value="button">按钮</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
          >
            <Select>
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PermissionManagement;